<template>
  <div>
    <basic-container>
      <avue-crud
        :option="tableOption"
        :data="tableData"
        :table-loading="tableLoading"
        :page="page"
        ref="crud"
        @size-change="sizeChange"
        @current-change="currentChange"
        @row-click="handleClick"
        @refresh-change="handleList"
      >
        <template slot-scope="scope" slot="no">
          <span
            style="color:blue; cursor:pointer;"
            @click="handleDetail(scope.row)"
          >{{scope.row.no}}</span>
        </template>

        <template slot-scope="scope" slot="menu" style="width:100px">
          <span style="margin-left:10px">
            <el-button type="primary" @click="handleDetail(scope.row)" size="small">查看</el-button>
          </span>
          <span style="margin-left:10px" v-if="scope.row.flag == 9">
            <el-button type="primary" @click="handleCancelConfirm(scope.row)" size="small">确认退订单</el-button>
          </span>
          <span style="margin-left:10px" v-if="isShip(scope.row.flag)">
            <el-button type="primary" @click="handleCommand({row:scope.row, type:'dada'})" size="small">发货</el-button>
            <!-- <el-dropdown style="margin-right:10px;" @command="handleCommand">
              <el-button type="primary" size="small">发货
                <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="{row:scope.row, type:'manual'}">自填快递单</el-dropdown-item>
                <el-dropdown-item :command="{row:scope.row, type:'dada'}">达达</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown> -->

            <!-- <el-dropdown @command="handleCommand(row)" size="small" split-button style="margin-right:10px;" type="primary">发货
              <el-dropdown-menu slot="dropdown" >
                <el-dropdown-item command="manual">自填快递单</el-dropdown-item>
                <el-dropdown-item command="dada">达达</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>-->
            <!-- <el-button type="primary" @click="handleShip(scope.row)" size="small">发货</el-button> -->
            <el-button type="danger" @click="handleCancel(scope.row)" size="small">取消订单</el-button>
          </span>
        </template>

        <template slot="menuLeft">
          <div class="el-form el-form--inline">
            <div class="el-form-item">
              <el-select v-model="orderFilter.flag" placeholder="请选择" @change="handleList(true)">
                <el-option
                  v-for="(item,index) in flagOptions"
                  :key="item"
                  :label="item"
                  :value="index"
                ></el-option>
              </el-select>
            </div>

            <div class="el-form-item">
              <el-date-picker
                v-model="orderFilter.datetime"
                type="daterange"
                @change="handleList(true)"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd"
              >></el-date-picker>
            </div>

            <div class="el-form-item">
              <el-input
                v-model="orderFilter.search"
                style="width:220px"
                placeholder="订单号，配送地址，产品名称"
              ></el-input>
            </div>
            <div class="el-form-item">
              <el-button type="primary" @click="handleList(true)">搜索</el-button>
            </div>
          </div>
        </template>

        <template slot-scope="scope" slot="is_ship">{{scope.row.is_ship ? '快递':'自取'}}</template>

        <template slot-scope="scope" slot="contact_name">{{scope.row.user.nickname}}</template>
        <template slot-scope="scope" slot="contact_phone">{{scope.row.user.phone}}</template>
        <template slot-scope="scope" slot="address">{{scope.row.address.address}}</template>

        <template slot-scope="scope" slot="flag">
          <span>{{scope.row.flag | flagDict}}</span>
        </template>
      </avue-crud>

      <!-- 填写发货相关信息 -->
      <el-dialog title="填写发货单" :visible.sync="showShip">
        <div>
          <h3 class="title">确定用户信息</h3>
          <el-row :span="20" v-if="selectData.address">
            <el-col :span="8">
              <span>联系人: {{selectAddress.contact_name}}</span>
            </el-col>
            <el-col :span="8">
              <span>联系电话: {{selectAddress.contact_phone}}</span>
            </el-col>
            <el-col :span="8">
              <span>详细地址: {{selectAddress.address}}</span>
            </el-col>
          </el-row>
        </div>
        <!-- 物流信息 -->
        <div>
          <div>
            <h3 class="title">填写物流信息</h3>
            <el-input type="textarea" :rows="6" placeholder="请输入物流信息" v-model="shipData"></el-input>
          </div>

          <div>
            <h3 class="title">订单退款</h3>
            <div>铜管退款：
              <el-form
                :inline="true"
                :model="refund.special"
                ref="special"
                class="demo-form-inline"
              >
                <el-form-item label="长度(米)" prop="len">
                  <el-input v-model="refund.special.len" style="width:80px;" placeholder="长度"></el-input>
                </el-form-item>
                <el-form-item label="公斤" prop="weigh">
                  <el-input v-model="refund.special.weigh" style="width:80px;" placeholder="公斤"></el-input>
                </el-form-item>
                <el-form-item label="金额(元)" prop="amt">
                  <el-input
                    type="number"
                    v-model="refund.special.amt"
                    style="width:120px;"
                    placeholder="金额"
                  ></el-input>
                </el-form-item>
              </el-form>
            </div>

            <div>普通商品退款
              <el-form :model="refund.common" ref="common">
                <el-form-item label="金额(元)" prop="amt">
                  <el-input
                    type="number"
                    v-model="refund.common.amt"
                    style="width:120px;"
                    placeholder="金额"
                  ></el-input>
                </el-form-item>
                <el-form-item label="退款备注" prop="remark">
                  <el-input
                    v-model="refund.common.remark"
                    type="textarea"
                    :rows="6"
                    placeholder="退款备注"
                    style="width:100%"
                  ></el-input>
                </el-form-item>
              </el-form>
            </div>
          </div>
          <div style="text-align:right">
            <!-- <el-button style="margin-top:30px;" type="danger" @click="handleRefundClick()">退款</el-button> -->
            <el-button style="margin-top:30px;" type="primary" @click="handleShipClick()">发货</el-button>
          </div>
        </div>
      </el-dialog>

      <refund ref="refund"></refund>
      <detail-edit ref="detail" type="1"></detail-edit>
      <detail-ship ref="detailShip" @refresh="handleList" type="1"></detail-ship>
    </basic-container>
  </div>
</template>

<script>
/* eslint-disable */
import { mapGetters } from "vuex";
import crudMixin from '@/mixins/crud'
import options from "./options.js";
import { isNull, arr2pojo, obj2pojo, validateResponse } from "@/util/util";
import { successMsg, errorMsg } from "@/util/message"
import { field, reField } from "./field";
import detailEdit from "@/views/merchant/common/detail_edit"
import shipDetail from "@/views/merchant/common/ship_detail"
import detailShip from "@/views/merchant/common/detail_ship"

import refund from "@/views/merchant/common/refund"

export default {
  name: "role",
  mixins: [crudMixin],
  components: {
    shipDetail, refund, detailEdit, detailShip
  },
  data() {
    return Object.assign({}, options, {
      orderFlag: 0,
      showShip: false,
      shipData: '',
      showDetail: false,
      orderFilter: {  //订单筛选
        flag: 0,
        datetime: [],
        search: ''
      },
      selectData: '',
      selectAddress: {
        name: '',
        phone: '',
        address: '',
      },
      flagOptions: [
        '全部订单', '待付款', '待发货', '已发货', '已完成', '已关闭', '取消申请中'
      ],
      refund_special: true,
      refund: {
        special: {
          len: 0,
          weigh: 0,
          amt: 0
        },
        common: {
          amt: 0,
          remark: ''
        }
      }
    })
  },
  created() {
    //初始化数据格式
    this.handleList();
  },
  watch: {
    "$route": "handleList"
  },
  mounted() { },
  computed: {
    showShipData() {
      if (isNull(this.selectData.ship_data)) 
      {
        return ''
      }

      let reg = new RegExp("\n", "g");
      let str = this.selectData.ship_data.replace(reg, "<br>");
      return str
    },
    validatespecial() {
      console.log(!isNull(this.refund.special.len))
      return (!isNull(this.refund.special.len)) && (!isNull(this.refund.special.len)) && (!isNull(this.refund.special.len))
    },
    validateCommon() {
      return (!isNull(this.refund.common.amt)) && (!isNull(this.refund.common.remark))
    }
  },
  filters: {
    flagDict: function (value) {
      var filter = options.tableOption.dicData.flag
      var str = ''
      filter.forEach(element => {
        if (value == element.value)        {
          str = element.label
        }
      });
      return str
    },
    numFilter: function (value) {
      let realVal = Number(value).toFixed(2)
      return realVal
    }
  },
  props: [],
  methods: {
    mapFlag(value) {
      var result = ''
      let flag = [
        { label: '待付款', value: 0 },
        { label: '订单取消', value: 1 },
        { label: '等待发货', value: 2 },
        { label: '等待发货', value: 3 },
        { label: '订单取消', value: 4 },
        { label: '待用户确认取消', value: 5 },
        { label: '订单取消', value: 6 },
        { label: '已发货', value: 7 },
        { label: '已完成', value: 8 },
        { label: '取消申请中', value: 9 },
      ]
      flag.forEach(element => {
        if (element.value == value)        {
          result = element.label
          return false
        }
      });

      return result
    },
    handleList(init = false) {
      this.tableLoading = true;
      let orderFlag = this.orderFlag = this.$route.query.flag;
      this.orderFlag = orderFlag

      if (init)
      {
        this.page.currentPage = 1
      }

      let param = Object.assign({
        flag: orderFlag,
        perPage: this.page.pageSize,
        page: this.page.currentPage
      }, this.orderFilter);
      var vm = this
      this.$store
        .dispatch("GetOrders", param)
        .then(
          res => {
            this.tableLoading = false;
            if (res.data.status == 1)            {
              let _data = res.data.result.data || []
              let _meta = res.data.result.meta || []

              this.tableData = _data;
              this.page.total = _meta.total;
            }
          }, error => {
            this.tableLoading = false;
          })
    },
    handleDetail(row) {
      this.$nextTick(() => {
        this.$refs.detail.handleShow(row.id)
      })
      // var vm = this
      // vm.showDetail = true
      // this.selectData = row
    },
    handleShip(row, type) {
      this.$nextTick(() => {
        this.$refs.detailShip.handleShow(row.id, type)
      })
      // var vm = this
      // vm.selectData = data
      // vm.selectAddress = data.address

      // if (!vm.selectData.is_ship)      {
      //   vm.shipAlert()
      // }
      // else      {
      //   vm.shipData = ''
      //   vm.showShip = true
      // }
    },
    handleShipClick() {
      this.$nextTick(() => {
        this.$refs.detailShip.handleShow(row.id)
      })
      //this.shipAlert()
    },
    search() {
      console.log(this.orderFilter)
    },
    shipAlert() {
      let vm = this
      let param = {
        id: this.selectData.id,
        ship_data: this.shipData
      }

      let needRefund = false
      let specialMsg = ''
      let commonMsg = ''
      let refund_param = {}
      //需要退铜管
      if (vm.refund_special)
      {
        if ((vm.refund.special.amt > 0) && (vm.refund.special.len > 0) && (vm.refund.special.weigh > 0))
        {
          needRefund = true
          specialMsg = `铜管长是${vm.refund.special.len}米，重量是${vm.refund.special.weigh}斤，退款金额为${vm.refund.special.amt}元`
          vm.refund.special.remark = specialMsg
          refund_param.special = vm.refund.special
        }
        else        {
          if ((vm.refund.special.amt > 0))
          {
            needRefund = false
            return errorMsg(vm, '铜管退款参数错误')
          }
        }
      }

      if (vm.refund.common.amt > 0)
      {
        if (isNull(vm.refund.common.remark))
        {
          return errorMsg(vm, '退款备注不能为空')
        }

        needRefund = true
        commonMsg = '普通商品退款' + vm.refund.common.amt + '元'
        refund_param.common = vm.refund.common
      }

      let message = '是否确认订单即将发货'
      //需要退款
      if (needRefund)
      {
        message = ''
        if (specialMsg != '')
        {
          message += specialMsg + '。\n'
        }
        if (commonMsg != '')
        {
          message += commonMsg + '。\n'
        }
        message += '是否确认订单即将发货。'
      }

      this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (needRefund)
        {
          //先退款，后发货
          vm.$store
            .dispatch("orderRefund", Object.assign({ id: vm.selectData.id, type: 1 }, refund_param))
            .then(
              res => {
                if (res.data.status == 1)                {
                  //进行发货操作
                  vm.shipThisOrder(param)
                }
                else                {
                  errorMsg(vm, res.data.message)
                }
              }
            )
        }
        else        {
          vm.shipThisOrder(param)
        }
      })


      /*
      this.$confirm('是否确定订单即将发货？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
      })
      */

      //进行退款请求
      /*
        vm.$store
          .dispatch("orderRefund", param)
          .then(
            res => {
              if (res.data.status == 1)              {
                //进行发货操作
                vm.$store
                  .dispatch("ShipOrder", param)
                  .then(
                    res => {
                      if (res.data.status == 1)                      {
                        vm.$message({
                          type: 'success',
                          message: '发货成功!'
                        });
                        vm.showShip = false
                        //直接对flag进行更改
                        let index = vm.selectData.$index
                        vm.tableData[index].flag = 7;  //修改成为已发货状态
                        vm.showShip = false

                        //vm.handleList()
                      }
                      else                      {
                        errorMsg(vm, res.data.message)
                      }
                    })
              }
              else              {
                errorMsg(vm, res.data.message)
              }
            }, error => {
            })
      }).catch(() => {
      });
      */
    },
    shipThisOrder(param) {
      let vm = this
      vm.$store
        .dispatch("ShipOrder", param)
        .then(
          res => {
            if (res.data.status == 1)            {
              vm.$message({
                type: 'success',
                message: '发货成功!'
              });
              vm.showShip = false
              //直接对flag进行更改
              let index = vm.selectData.$index
              vm.tableData[index].flag = 7;  //修改成为已发货状态
              vm.showShip = false
            }
            else            {
              return errorMsg(vm, res.data.message)
            }
          })
    },
    isShip: function (value) {
      if (value == 2) return true
      if (value == 3) return true
      return false
    },
    //取消订单按钮
    handleCancel(row) {
      let vm = this
      let param = {
        id: row.id,
      }
      vm.selectData = row
      let str = '是否取消订单？'
      if (! isNull(row.real_ship_at))
      {
        if(row.ship_extra.order_status== 2 || row.ship_extra.order_status== 3){
        str = '该订单取消将产生违约金！'
         }
      }
      
      this.$confirm(str, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        vm.$store.dispatch("CancelOrder", param).then(res => {
          if (res.data.status == 1)              
          {
            vm.$message({
              type: 'success',
              message: '取消订单成功!'
            });
            //直接对flag进行更改
            let index = vm.selectData.$index
            vm.tableData[index].flag = 5;  //修改成为取消订单确认
          }
          else              {
            errorMsg(vm, res.data.message)
          }
        }, error => {
        })
      }).catch(() => {
      });
    },
    handleCancelConfirm(row) {
      this.$confirm('是否确认用户可取消订单?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store
          .dispatch("orderCancelConfirm", { id: row.id })
          .then(res => {
            if (res.data.status == 1)            {
              this.$message({
                type: 'success',
                message: '订单已被取消!'
              });
              this.handleList()
            }
            else            {
              errorMsg(this, res.data.message)
            }
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    handleRefundClick(row) {
      this.$refs.refund.handleShow(row)
    },
    handleCommand(command) {
      this.handleShip(command.row,command.type)
    }
  }
};
</script>

<style lang="scss" scoped>
.table-container {
  padding: 8px 10px;
}
.cancel {
  color: #000;
}

.card:last-child {
  border-bottom: 0px;
}

.card {
  padding: 10px;
  // border: 1px solid #ebeef5;
  margin-bottom: 5px;
  border-bottom: 1px solid #ebeef5;
}

.card .title {
  font-weight: 600;
  font-style: normal;
  color: rgba(0, 0, 0, 0.847058823529412);
}

.flex {
  flex: 1;
  flex-direction: row;
}
</style>
